package me.hekr.demo;

import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.litesuits.android.log.Log;
import com.litesuits.common.assist.Toastor;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import me.hekr.hekrsdk.action.HekrUser;
import me.hekr.hekrsdk.action.HekrUserAction;
import me.hekr.hekrsdk.bean.DeviceBean;
import me.hekr.hekrsdk.listener.DataReceiverListener;
import me.hekr.hekrsdk.util.ConstantsUtil;
import me.hekr.hekrsdk.util.HekrCodeUtil;
import me.hekr.hekrsdk.util.MsgUtil;

public class DeviceCtrlActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "DeviceCtrlActivity";
    private String deviceTid;
    private String ctrlKey;
    private EditText command_tv;
    private List<MsgBean> list;
    private MyAdapter myAdapter;
    private ListView listView;
    private HekrUserAction hekrUserAction;
    private Toastor toastor;
    private ClipboardManager clipboardManager;
    private MsgBroadReceiver msgBroadReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_ctrl);
        initView();

        initData();
    }

    private void initView() {
        command_tv = (EditText) findViewById(R.id.send_input);
        listView = (ListView) findViewById(R.id.listview);

        Button send = (Button) findViewById(R.id.send);
        if (send != null) {
            send.setOnClickListener(this);
        }

        Button command_btn = (Button) findViewById(R.id.command_btn);
        if (command_btn != null) {
            command_btn.setOnClickListener(this);
        }
    }

    private void initData() {
        clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        hekrUserAction = HekrUserAction.getInstance(DeviceCtrlActivity.this);
        createBroadcast();
        toastor = new Toastor(this);
        list = new CopyOnWriteArrayList<>();
        myAdapter = new MyAdapter(list, this);
        if (listView != null) {
            listView.setAdapter(myAdapter);
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        Intent i = getIntent();
        deviceTid = i.getStringExtra("deviceTid");
        ctrlKey = i.getStringExtra("ctrlKey");

        //旧版使用方法
        /*if (!TextUtils.isEmpty(deviceTid) && !TextUtils.isEmpty(ctrlKey)) {
            JSONObject filter = new JSONObject();
            JSONObject params = new JSONObject();
            try {
                filter.put("action", "devSend");
                params.put("devTid", deviceTid);
                filter.put("params", params);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            MsgUtil.receiveMsg(this, filter, new DataReceiverListener() {
                @Override
                public void onReceiveSuccess(String msg) {
                    Log.i(TAG, "receive:onReceiveSuccess: " + msg);
                    //MsgBean msgBean = new MsgBean(MyAdapter.LEFT, msg);
                    //refresh(msgBean);
                }

                @Override
                public void onReceiveTimeout() {

                }
            });
        }*/

        //1.1.3新增使用方法
        if (!TextUtils.isEmpty(deviceTid)){

            MsgUtil.receiveDevSendMsg(this, deviceTid, new DataReceiverListener() {
                @Override
                public void onReceiveSuccess(String msg) {
                    Log.i(TAG, "receive:onReceiveSuccess: " + msg);
                }

                @Override
                public void onReceiveTimeout() {

                }
            });
        }

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(DeviceCtrlActivity.this);
                builder.setTitle("复制");
                builder.setItems(getResources().getStringArray(R.array.copy), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                String msg = list.get(position).getMsg();
                                copy(msg);
                                break;
                            case 1:
                                copyRaw(list.get(position));
                                break;
                            case 2:
                                break;
                        }
                    }
                });
                builder.create().show();
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send:
                String command_str = command_tv.getText().toString().trim();

                //旧版使用方法
                /*if (!TextUtils.isEmpty(deviceTid) && !TextUtils.isEmpty(ctrlKey) && !TextUtils.isEmpty(command_str)) {
                    JSONObject command = new JSONObject();
                    JSONObject params = new JSONObject();
                    JSONObject data = new JSONObject();
                    try {
                        //480C01000101000000000057协议
                        data.put("raw", command_str);
                        params.put("data", data);

                        //json透传
                        //params.put("data",new JSONObject(command_str));

                        params.put("devTid", deviceTid);
                        params.put("ctrlKey", ctrlKey);

                        command.put("action", "appSend");
                        command.put("params", params);
                        MsgBean ms = new MsgBean(MyAdapter.RIGHT, command.toString());
                        refresh(ms);

                        MsgUtil.sendMsg(this, deviceTid, command, new DataReceiverListener() {
                            @Override
                            public void onReceiveSuccess(String msg) {
                                //MsgBean receive = new MsgBean(MyAdapter.LEFT, msg);
                                //refresh(receive);
                            }

                            @Override
                            public void onReceiveTimeout() {
                                Log.e(TAG, "send:onReceiveSuccess: 超时");
                                //MsgBean receive = new MsgBean(MyAdapter.LEFT, "超时");
                                //refresh(receive);

                                hekrUserAction.getDevices(deviceTid, new HekrUser.GetDevicesListener() {
                                    @Override
                                    public void getDevicesSuccess(List<DeviceBean> devicesLists) {
                                        Log.d(TAG, "列举设备成功！  ");
                                        if (devicesLists != null && !devicesLists.isEmpty()) {
                                            DeviceBean deviceBean = devicesLists.get(0);
                                            if (deviceBean != null && !deviceBean.isOnline()) {
                                                toastor.showSingletonToast("设备离线!");
                                                finish();
                                            }
                                        }
                                    }

                                    @Override
                                    public void getDevicesFail(int errorCode) {
                                        Log.e(TAG, HekrCodeUtil.errorCode2Msg(errorCode));
                                    }
                                });
                            }
                        }, false);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e(TAG, "请检查deviceTid||command||ctrlKey是否为空!");
                }*/
                //1.1.3新增使用方法
                if (!TextUtils.isEmpty(deviceTid) && !TextUtils.isEmpty(ctrlKey) && !TextUtils.isEmpty(command_str)) {
                    int commandType;
                    if(command_str.startsWith("48")){
                        commandType=MsgUtil.PASSTHROUGH;
                    }else{
                        commandType=MsgUtil.MASTERCONTROL;
                    }
                    MsgBean ms = new MsgBean(MyAdapter.RIGHT, command_str);
                    refresh(ms);
                    MsgUtil.sendMsg(this, deviceTid, ctrlKey,true,commandType,command_str, new DataReceiverListener() {
                        @Override
                        public void onReceiveSuccess(String msg) {

                        }

                        @Override
                        public void onReceiveTimeout() {
                            Log.e(TAG, "send:onReceiveSuccess: 超时");

                            hekrUserAction.getDevices(deviceTid, new HekrUser.GetDevicesListener() {
                                @Override
                                public void getDevicesSuccess(List<DeviceBean> devicesLists) {
                                    Log.d(TAG, "列举设备成功！  ");
                                    if (devicesLists != null && !devicesLists.isEmpty()) {
                                        DeviceBean deviceBean = devicesLists.get(0);
                                        if (deviceBean != null && !deviceBean.isOnline()) {
                                            toastor.showSingletonToast("设备离线!");
                                            finish();
                                        }
                                    }
                                }

                                @Override
                                public void getDevicesFail(int errorCode) {
                                    Log.e(TAG, HekrCodeUtil.errorCode2Msg(errorCode));
                                }
                            });
                        }
                    });
                }else {
                    Log.e(TAG, "请检查deviceTid||command||ctrlKey是否为空!");
                }

                break;
            case R.id.command_btn:
                if (command_tv != null && clipboardManager != null) {
                    try {
                        command_tv.setText(clipboardManager.getPrimaryClip().getItemAt(0).getText().toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }


    /**
     * 刷新ListView
     *
     * @param msgBean msgBean
     */
    private void refresh(final MsgBean msgBean) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.add(msgBean);
                myAdapter.notifyDataSetChanged();
                listView.setSelection(list.size() - 1);
            }
        });
    }


    /**
     * 复制raw操作
     */
    private void copyRaw(MsgBean msgBean) {
        String str = msgBean.getMsg();
        try {
            JSONObject object = new JSONObject(str);
            if (object.has("params")) {
                String raw = object.getJSONObject("params").getJSONObject("data").getString("raw");
                copy(raw);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    /**
     * 复制操作
     */
    private void copy(String str) {
        ClipData myClip = ClipData.newPlainText("text", str);
        clipboardManager.setPrimaryClip(myClip);
        toastor.showSingleLongToast("复制" + str + "成功！");
    }


    /**
     * 创建广播接收器，用来接收SDK中发出的webSocket
     */
    private void createBroadcast() {
        msgBroadReceiver = new MsgBroadReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstantsUtil.ActionStrUtil.ACTION_WS_DATA_RECEIVE);    //只有持有相同的action的接受者才能接收此广播
        registerReceiver(msgBroadReceiver, filter);
    }

    /**
     * 云端回复的广播接收器
     */
    class MsgBroadReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("broadReceiver", intent.getStringExtra(ConstantsUtil.HEKR_WS_PAYLOAD));
            String str = intent.getStringExtra(ConstantsUtil.HEKR_WS_PAYLOAD);
            if (!TextUtils.isEmpty(str)) {
                MsgBean receive = new MsgBean(MyAdapter.LEFT, str);
                refresh(receive);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (msgBroadReceiver != null) {
            unregisterReceiver(msgBroadReceiver);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_device_ctrl, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_clear) {
            list.clear();
            myAdapter.notifyDataSetChanged();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
